<?php

namespace App\Support\Singleton;

class SingletonInstance
{
    public static ?SingletonInstanceMap $instanceMap = null;

    private function __construct() {
        if(method_exists($this, "init")){
            $this->init();
        }
    }

    /**
     * @param bool $singleton
     * @return static
     */
    public static function getInstance(bool $singleton = false): self
    {
        if (is_null(self::$instanceMap)) {
            self::$instanceMap = new SingletonInstanceMap();
        }

        if ($singleton) {
            $singletonKey = md5(static::class);

            if (! property_exists(self::$instanceMap, $singletonKey)) {
                self::$instanceMap->{$singletonKey} = new static();
            }

            return self::$instanceMap->{$singletonKey};
        } else {
            return new static();
        }

    }
}
